package cfdt.common.exception;

import cfdt.common.enums.ICodeEnum;
import cfdt.common.utils.CommonUtils;
import lombok.Getter;

/**
 * 带响应码的异常类
 * 
 * <pre>
 * Modify Information:
 * Author       Date        Description
 * ============ =========== ============================
 * zhangxing    2009-05-04  Create this file
 * 
 * </pre>
 * 
 */
@Getter
public class CodeException extends RuntimeException {
    private static final long serialVersionUID = 7724252889850188629L;

    /**
     * 响应码
     */
    private final String code;

    /**
     * 响应码提示信息
     */
    private String message;

    /**
     * 业务异常，响应码直接创建
     * </br> 业务逻辑禁止使用，统一使用枚举创建
     *
     * @param code 响应码
     * @param message 响应码提示信息
     */
    public CodeException(String code, String message) {
        super(message);
        this.code = code;
    }


    /**
     * 业务异常-枚举创建-无参数
     * @param codeEnum 响应码枚举
     */
    public CodeException(ICodeEnum codeEnum) {
        this.code = codeEnum.getCode();
        this.message = codeEnum.getDesc();
    }

    public CodeException(ICodeEnum codeEnum, Throwable cause) {
        super(codeEnum.getDesc(), cause);
        this.code = codeEnum.getCode();
    }

    /**
     * 业务异常-枚举创建-有参数
     * @param codeEnum 响应码枚举
     * @param errorArgs 错误响应描述参数
     */
    public CodeException(ICodeEnum codeEnum, Object... errorArgs) {
        this.code = codeEnum.getCode();
        this.message = CommonUtils.getCodeMessage(codeEnum.getDesc(), errorArgs);
    }

    public CodeException(ICodeEnum codeEnum, Throwable cause, Object... errorArgs) {
        super(CommonUtils.getCodeMessage(codeEnum.getDesc(), errorArgs), cause);
        this.code = codeEnum.getCode();
    }

    /**
     * 断言异常(如果不为真，抛出异常)-枚举创建-无参数
     * @param condition 判断条件
     * @param codeEnum
     */
    public static void isTrue(boolean condition, ICodeEnum codeEnum, Object... errorArgs) {
        if (condition) {
            return;
        }
        throw new CodeException(codeEnum, errorArgs);
    }

    /**
     * 断言异常(如果不为真，抛出异常)-枚举创建-有参数
     * @param condition
     * @param codeEnum
     */
    public static void isTrue(boolean condition, ICodeEnum codeEnum) {
        if (condition) {
            return;
        }
        throw new CodeException(codeEnum);
    }

    

}
